package com.hua.store.service.impl;

import com.hua.store.dao.OrderDao;
import com.hua.store.dao.UserDao;
import com.hua.store.dao.impl.OrderDaoImpl;
import com.hua.store.domin.OrderItem;
import com.hua.store.domin.Orders;
import com.hua.store.domin.PageModel;
import com.hua.store.domin.User;
import com.hua.store.service.OrderService;
import com.hua.store.utils.JDBCUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    @Override
    public void saveOrder(Orders orders) throws Exception {
        try {
            JDBCUtils.startTransaction();
            OrderDao dao = new OrderDaoImpl();
            dao.saveOrder(orders);
            for (OrderItem orderItem : orders.getList()) {
                dao.saveOrderItem(orderItem);
            }
            JDBCUtils.commitAndClose();
        } catch (Exception e) {
            e.printStackTrace();
            JDBCUtils.rollbackAndClose();
        }
    }

    @Override
    public PageModel findOrdersByUidWithPage(User user, int curNum) throws Exception {
        OrderDao dao = new OrderDaoImpl();
        int totalRecords = dao.findTotalRecordsByUid(user);
        PageModel pm = new PageModel(curNum, 3, totalRecords);
        //找出吗每页的数据
        List<Orders> list = dao.findOrdersByUidWithPage(user, pm);
        pm.setList(list);
        pm.setUrl("OrderServlet?method=findOrdersByUidWithPage");
        return pm;
    }

    @Override
    public Orders findOrderByOid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {
        OrderDao dao = new OrderDaoImpl();
        Orders orders = dao.findOrderByOid(oid);
        return orders;
    }

    @Override
    public void updateOrder(Orders orders) throws SQLException {
        OrderDao dao = new OrderDaoImpl();
        dao.updateOrder(orders);
    }

    @Override
    public List<Orders> findAllOrder() throws SQLException {
        OrderDao dao = new OrderDaoImpl();
        return dao.findAllOrder();
    }

    @Override
    public List<Orders> findAllOrder(String state) throws SQLException {
        OrderDao dao = new OrderDaoImpl();
        return dao.findAllOrder(state);
    }
}
